import React, { FC, ReactElement, ReactNode, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

interface IProps {
  /** 跳转到指定页面所需要的时间 (单位：秒) */
  duration: number;
  /** 跳转到的页面路径字符串 */
  navigatePath: string;
  /** 提示信息 */
  message: ReactNode;
}

const defaultProps: Required<IProps> = {
  duration: 5,
  navigatePath: '/',
  message: '页面未找到！'
};

const NotFoundComponent: FC<Partial<IProps>> = (props): ReactElement => {
  const {
    duration: defaultDuration,
    navigatePath,
    message,
  } = {
    ...defaultProps,
    ...props,
  };

  const routeNavigate = useNavigate();
  const [duration, setDuration] = useState(defaultDuration);

  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;

    timer = setInterval(() => {
      if (duration > 1) {
        setDuration(d => d - 1);
      } else {
        if (timer) {
          clearInterval(timer);
          timer = null;
        }
        routeNavigate(navigatePath);
      }
    }, 1000);

    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    }
  }, [duration, navigatePath]);

  return (
    <div style={{ width: '100%', textAlign: 'center', margin: '50px auto' }}>
      <svg width="360" height="360" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="50" fill="#f0f0f0" />
        <path d="M50 20c-11.028 0-20 8.972-20 20s8.972 20 20 20 20-8.972 20-20-8.972-20-20-20zm0 35c-7.18 0-13-5.82-13-13s5.82-13 13-13 13 5.82 13 13-5.82 13-13 13z" fill="#333" />
        <path d="M50 50l15 15M50 50l-15 15" stroke="#333" strokeWidth="3" strokeLinecap="round" />
        <text x="20" y="80" fontFamily="Arial" fontSize="12" fill="#333">{message}</text>
      </svg>
      <p>{duration}秒后跳转回到首页</p>
    </div>
  );
}

export default NotFoundComponent;
